package com.vieewer.btdemo.view.camera;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.*;

import java.util.List;
import java.util.Locale;
import java.util.Set;

import com.lindroid.androidutilskt.statics.AppManager;
import com.vieewer.btdemo.R;
import com.vieewer.btdemo.base.BaseActivity;
import com.vieewer.btdemo.view.camera.dialog.PickerDialog;
import com.vieewer.btdemo.view.camera.dialog.SimplePickerDialog;
import com.vieewer.btdemo.view.camera.options.AspectRatioItem;
import com.vieewer.btdemo.view.camera.options.Commons;
import com.vieewer.btdemo.view.camera.options.SizeItem;
import com.vieewer.btdemo.view.microsoft.ocr.OcrActivity;
import org.jetbrains.annotations.NotNull;
import top.defaults.camera.CameraView;
import top.defaults.camera.CanvasDrawer;
import top.defaults.camera.Error;
import top.defaults.camera.Photographer;
import top.defaults.camera.PhotographerFactory;
import top.defaults.camera.PhotographerHelper;
import top.defaults.camera.SimpleOnEventListener;
import top.defaults.camera.Size;
import top.defaults.camera.Utils;
import top.defaults.camera.Values;

public class PhotographerActivity extends BaseActivity {

    Photographer photographer;
    PhotographerHelper photographerHelper;
    private boolean isRecordingVideo;

    CameraView preview;
    TextView statusTextView;

    TextView chooseSizeButton;
    TextView flashTextButton;
    ImageView flashTorch;
    TextView switchButton;
    ImageView actionButton;
    ImageView flipButton;
    TextView zoomValueTextView;

    TextView chooseRatio;
    TextView chooseSize;
    CheckBox fillSpace;
    CheckBox enableZoom;
    TextView flash;
    ImageView action;
    ImageView flip;

    ImageView flash_torch;
    TextView switch_mode;


    private String mPhotoFilePath;


    private int currentFlash = Values.FLASH_AUTO;

    private static final int[] FLASH_OPTIONS = {
            Values.FLASH_AUTO,
            Values.FLASH_OFF,
            Values.FLASH_ON,
    };

    private static final int[] FLASH_ICONS = {
            R.drawable.ic_flash_auto,
            R.drawable.ic_flash_off,
            R.drawable.ic_flash_on,
    };

    private static final int[] FLASH_TITLES = {
            R.string.flash_auto,
            R.string.flash_off,
            R.string.flash_on,
    };

    private boolean mHasFocus;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_record);
        initViews();
        initListeners();
        preview.setFillSpace(true);
        preview.setFocusIndicatorDrawer(new CanvasDrawer() {
            private static final int SIZE = 300;
            private static final int LINE_LENGTH = 50;

            @Override
            public Paint[] initPaints() {
                Paint focusPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
                focusPaint.setStyle(Paint.Style.STROKE);
                focusPaint.setStrokeWidth(2);
                focusPaint.setColor(Color.WHITE);
                return new Paint[]{ focusPaint };
            }

            @Override
            public void draw(Canvas canvas, Point point, Paint[] paints) {
                if (paints == null || paints.length == 0) return;

                int left = point.x - (SIZE / 2);
                int top = point.y - (SIZE / 2);
                int right = point.x + (SIZE / 2);
                int bottom = point.y + (SIZE / 2);

                Paint paint = paints[0];

                canvas.drawLine(left, top + LINE_LENGTH, left, top, paint);
                canvas.drawLine(left, top, left + LINE_LENGTH, top, paint);

                canvas.drawLine(right - LINE_LENGTH, top, right, top, paint);
                canvas.drawLine(right, top, right, top + LINE_LENGTH, paint);

                canvas.drawLine(right, bottom - LINE_LENGTH, right, bottom, paint);
                canvas.drawLine(right, bottom, right - LINE_LENGTH, bottom, paint);

                canvas.drawLine(left + LINE_LENGTH, bottom, left, bottom, paint);
                canvas.drawLine(left, bottom, left, bottom - LINE_LENGTH, paint);
            }
        });
        photographer = PhotographerFactory.createPhotographerWithCamera2(this, preview);
        photographerHelper = new PhotographerHelper(photographer);
        photographerHelper.setFileDir(Commons.MEDIA_DIR);
        photographer.setOnEventListener(new SimpleOnEventListener() {
            @Override
            public void onDeviceConfigured() {
                if (photographer.getMode() == Values.MODE_VIDEO) {
                    actionButton.setImageResource(R.drawable.record);
                    chooseSizeButton.setText(R.string.video_size);
                    switchButton.setText(R.string.video_mode);
                } else {
                    actionButton.setImageResource(R.drawable.ic_camera);
                    chooseSizeButton.setText(R.string.image_size);
                    switchButton.setText(R.string.image_mode);
                }
            }

            @Override
            public void onZoomChanged(float zoom) {
                zoomValueTextView.setText(String.format(Locale.getDefault(), "%.1fX", zoom));
            }

            @Override
            public void onStartRecording() {
                switchButton.setVisibility(View.INVISIBLE);
                flipButton.setVisibility(View.INVISIBLE);
                actionButton.setEnabled(true);
                actionButton.setImageResource(R.drawable.stop);
                statusTextView.setVisibility(View.VISIBLE);
            }

            @Override
            public void onFinishRecording(String filePath) {
                announcingNewFile(filePath);
                Toast.makeText(PhotographerActivity.this, "录像成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onShotFinished(String filePath) {
                mPhotoFilePath = filePath;
                announcingNewFile(filePath);
                Toast.makeText(PhotographerActivity.this, "拍照成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(Error error) {
                Log.e("Error happens: %s", error.getMessage());
            }
        });

        //设置初始化相机模式
        if (photographer.getMode() == Values.MODE_VIDEO) {
            photographerHelper.switchMode();
        }
        //设置使能缩放
        enableZoom.setChecked(true);
        preview.setPinchToZoom(true);

    }

    private void initListeners() {
        TextView add_zoomValue = findViewById(R.id.add_zoomValue);
        add_zoomValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float zoom = photographer.getZoom();
                photographer.setZoom(zoom + 1);

                photographer.refreshView(zoom + 1);
            }
        });

        TextView reduce_zoomValue = findViewById(R.id.reduce_zoomValue);
        reduce_zoomValue.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                float zoom = photographer.getZoom();
                photographer.setZoom(zoom - 1);

                photographer.refreshView(zoom -1);
            }
        });



        chooseRatio.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                List<AspectRatioItem> supportedAspectRatios = Commons.wrapItems(photographer.getSupportedAspectRatios(), AspectRatioItem::new);
                if (supportedAspectRatios != null) {
                    SimplePickerDialog<AspectRatioItem> dialog = SimplePickerDialog.create(new PickerDialog.ActionListener<AspectRatioItem>() {
                        @Override
                        public void onCancelClick(PickerDialog<AspectRatioItem> dialog) { }

                        @Override
                        public void onDoneClick(PickerDialog<AspectRatioItem> dialog) {
                            AspectRatioItem item = dialog.getSelectedItem(AspectRatioItem.class);
                            photographer.setAspectRatio(item.get());
                        }
                    });
                    dialog.setItems(supportedAspectRatios);
                    dialog.setInitialItem(Commons.findEqual(supportedAspectRatios, photographer.getAspectRatio()));
                    dialog.show(getFragmentManager(), "aspectRatio");
                }
            }
        });

        chooseSize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Size selectedSize = null;
                List<SizeItem> supportedSizes = null;
                int mode = photographer.getMode();
                if (mode == Values.MODE_VIDEO) {
                    Set<Size> videoSizes = photographer.getSupportedVideoSizes();
                    selectedSize = photographer.getVideoSize();
                    if (videoSizes != null && videoSizes.size() > 0) {
                        supportedSizes = Commons.wrapItems(videoSizes, SizeItem::new);
                    }
                } else if (mode == Values.MODE_IMAGE) {
                    Set<Size> imageSizes = photographer.getSupportedImageSizes();
                    selectedSize = photographer.getImageSize();
                    if (imageSizes != null && imageSizes.size() > 0) {
                        supportedSizes = Commons.wrapItems(imageSizes, SizeItem::new);
                    }
                }

                if (supportedSizes != null) {
                    SimplePickerDialog<SizeItem> dialog = SimplePickerDialog.create(new PickerDialog.ActionListener<SizeItem>() {
                        @Override
                        public void onCancelClick(PickerDialog<SizeItem> dialog) { }

                        @Override
                        public void onDoneClick(PickerDialog<SizeItem> dialog) {
                            SizeItem sizeItem = dialog.getSelectedItem(SizeItem.class);
                            if (mode == Values.MODE_VIDEO) {
                                photographer.setVideoSize(sizeItem.get());
                            } else {
                                photographer.setImageSize(sizeItem.get());
                            }
                        }
                    });
                    dialog.setItems(supportedSizes);
                    dialog.setInitialItem(Commons.findEqual(supportedSizes, selectedSize));
                    dialog.show(getFragmentManager(), "cameraOutputSize");
                }
            }
        });


        fillSpace.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                preview.setFillSpace(checked);
            }
        });



        enableZoom.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean checked) {
                preview.setPinchToZoom(checked);
            }
        });

        flash.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                currentFlash = (currentFlash + 1) % FLASH_OPTIONS.length;
                flashTextButton.setText(FLASH_TITLES[currentFlash]);
                flashTextButton.setCompoundDrawablesWithIntrinsicBounds(FLASH_ICONS[currentFlash], 0, 0, 0);
                photographer.setFlash(FLASH_OPTIONS[currentFlash]);
            }
        });

        flip.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                photographerHelper.flip();
            }
        });

        action.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int mode = photographer.getMode();
                if (mode == Values.MODE_VIDEO) {
                    if (isRecordingVideo) {
                        finishRecordingIfNeeded();
                    } else {
                        isRecordingVideo = true;
                        photographer.startRecording(null);
                        actionButton.setEnabled(false);
                    }
                } else if (mode == Values.MODE_IMAGE) {
                    photographer.takePicture();
                }
            }
        });


        flash_torch.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int flash = photographer.getFlash();
                if (flash == Values.FLASH_TORCH) {
                    photographer.setFlash(currentFlash);
                    flashTextButton.setEnabled(true);
                    flashTorch.setImageResource(R.drawable.light_off);
                } else {
                    photographer.setFlash(Values.FLASH_TORCH);
                    flashTextButton.setEnabled(false);
                    flashTorch.setImageResource(R.drawable.light_on);
                }
            }
        });

        switch_mode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                photographerHelper.switchMode();
            }
        });


    }

    private void initViews() {

        preview = findViewById(R.id.preview);
        statusTextView = findViewById(R.id.status);
        chooseSizeButton = findViewById(R.id.chooseSize);
        flashTextButton = findViewById(R.id.flash);
        flashTorch = findViewById(R.id.flash_torch);
        switchButton = findViewById(R.id.switch_mode);
        actionButton = findViewById(R.id.action);
        flipButton = findViewById(R.id.flip);
        zoomValueTextView = findViewById(R.id.zoomValue);
        chooseRatio = findViewById(R.id.chooseRatio);
        chooseSize = findViewById(R.id.chooseSize);
        fillSpace = findViewById(R.id.fillSpace);
        enableZoom = findViewById(R.id.enableZoom);
        flash = findViewById(R.id.flash);
        action = findViewById(R.id.action);
        flip = findViewById(R.id.flip);
        flash_torch = (ImageView) findViewById(R.id.flash_torch);
        switch_mode = (TextView)findViewById(R.id.switch_mode);

    }

    @Override
    protected void onResume() {
        super.onResume();
        enterFullscreen();
        photographer.startPreview();
    }

    @Override
    protected void onPause() {
        finishRecordingIfNeeded();
        photographer.stopPreview();
        super.onPause();
    }

    private void enterFullscreen() {
        View decorView = getWindow().getDecorView();
        decorView.setBackgroundColor(Color.BLACK);
        int uiOptions = View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                | View.SYSTEM_UI_FLAG_FULLSCREEN
                | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY;
        decorView.setSystemUiVisibility(uiOptions);
    }

    private void finishRecordingIfNeeded() {
        if (isRecordingVideo) {
            isRecordingVideo = false;
            photographer.finishRecording();
            statusTextView.setVisibility(View.INVISIBLE);
            switchButton.setVisibility(View.VISIBLE);
            flipButton.setVisibility(View.VISIBLE);
            actionButton.setEnabled(true);
            actionButton.setImageResource(R.drawable.record);
        }
    }

    private void announcingNewFile(String filePath) {
        //Toast.makeText(PhotographerActivity.this, "File: " + filePath, Toast.LENGTH_SHORT).show();
        Utils.addMediaToGallery(PhotographerActivity.this, filePath);
    }

/*    @Override
    public void onBackPressed() {
        //如果来自翻译orc拍照
        if (getIntent().getIntExtra("tag", 0) == 1) {
            Intent intent = new Intent(this, OcrActivity.class);
            intent.putExtra("file", mPhotoFilePath);
            //setResult(1, intent);
            startActivity(intent);
        }
        finish();
        super.onBackPressed();
    }*/


    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        mHasFocus = hasFocus;
        super.onWindowFocusChanged(hasFocus);
    }

    @Override
    public boolean onKeyUp(int keyCode, KeyEvent event) {
        Log.i("yjj", "" + photographer.getMode() + "currentActivity >>>" +  AppManager.currentActivity().getLocalClassName());

        if (photographer != null && mHasFocus && AppManager.currentActivity().getLocalClassName().equals("view.camera.PhotographerActivity")) {
            float zoom = photographer.getZoom();

            if (keyCode == 22) {        //触控板往前滑动
                if (zoom < 6) {
                    zoom ++;
                    photographer.setZoom(zoom);
                }
            } else if (keyCode == 21) { //触控板往后滑动
                if (zoom > 1) {
                    zoom --;
                    photographer.setZoom(zoom);
                }
            }
            photographer.refreshView(zoom);


            //按功能键切换拍照和录像模式
            if (keyCode == 119) {  //Fn按键对应键值为119
                if (isRecordingVideo) {
                    finishRecordingIfNeeded();
                }
                photographerHelper.switchMode();
                Log.i("yjj", "PhotographerActivity onKeyUp camera capture");
            }

        }

        return super.onKeyUp(keyCode, event);
    }


    public static void startActivity(@NotNull Activity activity, int tag) {
        Intent intent = new Intent(activity, PhotographerActivity.class);
        intent.putExtra("tag", tag);
        activity.startActivity(intent);
    }



}
